<template>
    <div class="login zw-img-bg">
        <div class="login-panel">
            <div class="title">客易达商城管理系统</div>
            <el-form :model="form" :rules="rules" ref="formRef" label-width="0" size="large" class="login-form">
                <el-form-item label="" prop="username">
                    <el-input v-model.trim="form.username" placeholder="您的姓名" maxlength="50" />
                </el-form-item>
                <el-form-item label="" prop="mobile">
                    <el-input v-model.trim="form.mobile" placeholder="手机号" />
                </el-form-item>
                <el-form-item label="" prop="smsCode">
                    <SmsCode v-model.trim="form.smsCode" :mobile="form.mobile" from="register" />
                </el-form-item>
                <el-form-item label="" prop="password">
                    <el-input
                        type="password"
                        v-model="form.password"
                        show-password
                        autocomplete="new-password"
                        placeholder="8-16位密码，区分大小写" />
                </el-form-item>
                <el-form-item label="" prop="repeatPassword">
                    <el-input type="password" v-model="form.repeatPassword" show-password placeholder="确认密码" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" :disabled="isDisabled" class="login-submit" @click="submitHandler">
                        注 册
                    </el-button>
                    <div class="register">
                        <span class="no-accout">已有账户？</span>
                        <el-button type="primary" class="register-btn" text @click="loginHandler">立即登录</el-button>
                    </div>
                </el-form-item>
                <el-form-item>
                    <div class="agreement-area">
                        <el-checkbox label="" v-model="remind" size="small" class="checkbox"></el-checkbox>
                        <div class="agreement">
                            <span>我已阅读并确认接受</span>
                            <span class="agreement-text" @click="viewAgreementHandler('service')">
                                《客易达微商城服务协议》
                            </span>
                            <span class="agreement-text" @click="viewAgreementHandler('privacy')">
                                《客易达微商城隐私条款》
                            </span>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { computed, reactive, ref, inject } from 'vue';
import { useRouter } from 'vue-router';
import request from '@/request';
import SmsCode from '@/components/SmsCode.vue';
import { isMobile, isPassword, isEmpty, isNotEmpty } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import storage from '@/commons/storage';

const bus = inject('bus');
const router = useRouter();

const remind = ref(false);
const formRef = ref(null);
const form = reactive({
    username: '',
    password: '',
    repeatPassword: '',
    mobile: '',
    smsCode: ''
});

/**
 * 校验确认密码
 * @param {*} rule
 * @param {*} value
 * @param {*} callback
 */
const validateRepeatPassword = (rule, value, callback) => {
    if (isPassword(value) && isNotEmpty(form.password) && form.repeatPassword !== form.password) {
        callback(new Error('两次密码输入不一致!'));
    } else {
        callback();
    }
};

/**
 * 密码规则校验
 * @param {*} rule
 * @param {*} value
 * @param {*} callback
 */
const validatePasswordRule = (rule, value, callback) => {
    if (isPassword(value)) {
        callback();
    } else {
        callback(new Error('长度8-16个字符，由数字或字母组成且不能有特殊字符'));
    }
};

/**
 * 校验手机号
 * @param {*} rule
 * @param {*} value
 * @param {*} callback
 */
const validatePhone = (rule, value, callback) => {
    if (isMobile(value)) {
        callback();
    } else {
        callback(new Error('请输入正确的手机号!'));
    }
};

const rules = reactive({
    username: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { max: 50, message: '长度不能超过50字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { validator: validatePasswordRule, trigger: 'blur' }
    ],
    repeatPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { validator: validatePasswordRule, trigger: 'blur' },
        { validator: validateRepeatPassword, trigger: 'blur' },
        { validator: validateRepeatPassword, trigger: 'change' }
    ],
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validatePhone, trigger: 'blur' }
    ],
    smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
});

const isDisabled = computed(() => {
    let ret = false;
    for (let key in form) {
        if (isEmpty(form[key])) {
            ret = true;
            break;
        }
    }
    return ret;
});

/**
 * 执行注册
 */
const submitHandler = async () => {
    if (!remind.value) {
        ElMessage.error('请先阅读并勾选用户隐私协议');
        return;
    } else {
        formRef.value.validate(async valid => {
            if (valid) {
                if (form.password === form.repeatPassword) {
                    const res = await request('registerServ', form);
                    const { token } = res.data;
                    storage.set('ZW-TOKEN', token);
                    router.push('/company');
                } else {
                    formRef.value.validateField('repeatPassword');
                }
            }
        });
    }
};

/**
 * 去登录
 */
const loginHandler = () => {
    router.push('/login');
};

/**
 * 查看协议
 */
const viewAgreementHandler = type => {
    window.open(`/docs/${type}.pdf`);
};

bus.off('sendSms:register');
bus.on('sendSms:register', () => {
    setTimeout(() => {
        formRef.value.validateField('mobile');
    }, 0);
});
</script>
<style lang="scss" src="./style.scss" scoped></style>
